//
// Create by Zeng Yun on 2018/12/24
//
// 场景执行

package home

import (
	"adai.design/jarvis/common/log"
	"adai.design/jarvis/home/model"
	"adai.design/jarvis/member"
	"encoding/json"
	"fmt"
)

type SceneManager struct {
	scenes []*model.Scene
}

func (sm *SceneManager) execute(h *Home, id string) error {
	var scene *model.Scene = nil
	for _, s := range sm.scenes {
		if s.Id == id {
			scene = s
			break
		}
	}
	if scene == nil {
		return fmt.Errorf("404-not-found")
	}
	return h.containerManager.executeActions(h, scene.Actions...)
}

type ScenePost struct {
	Type  string          `json:"type"`
	Scene string          `json:"scene"`
	Data  json.RawMessage `json:"data,omitempty"`
}

const scenePostExecute = "execute"

func (sm *SceneManager) memberPkgHandle(h *Home, pkg *member.MessagePkg) error {
	if pkg.Msg.Method == member.MsgMethodPost {
		var post ScenePost
		if err := json.Unmarshal(pkg.Msg.Data, &post); err != nil {
			log.Error("json parse failed: %s", err)
			return err
		}
		if post.Type == scenePostExecute {
			err := sm.execute(h, post.Scene)
			reply := &member.MessagePkg{
				Type: pkg.Type,
				Ctx:  pkg.Ctx,
				Msg: &member.Message{
					Path:   pathScene,
					Method: member.MsgMethodPost,
				},
			}
			if err == nil {
				reply.Msg.State = "ok"
			} else {
				reply.Msg.State = err.Error()
			}
			h.replyMemberResult(reply)
		}
	}
	return nil
}
